class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }

        ListNode pA = headA;
        ListNode pB = headB;
            //遍历链表直到两个指针相遇，或者两个链表遍历完毕
        while (pA != pB) {
            //如果当前指针到达链表末尾，则切换到另一个链表
            pA = (pA == null) ? headB : pA.next;
            pB = (pB == null) ? headA : pB.next;
        }
// pA == pB 为 null 或者相交的节点
        return pA;
    }
}